<template>
  <view class="payment-page">
    <!-- 页面头部 -->
    <u-navbar
      title="费用详情"
      :left-icon-size="22"
      left-text="返回"
      @left-click="handleBack"
      :background="{ backgroundColor: '#007aff' }"
      :title-style="{ color: '#fff' }"
      :left-text-style="{ color: '#fff' }"
    />
    
    <!-- 费用信息卡片 -->
    <view class="fee-info-section" v-if="feeInfo">
      <view class="fee-card">
        <view class="fee-header">
          <text class="fee-title">{{ feeInfo.feeName }}</text>
          <u-tag :text="feeInfo.feeTypeName" type="primary" size="mini"></u-tag>
        </view>
        <view class="fee-details">
          <view class="detail-item">
            <text class="label">计费周期：</text>
            <text class="value">{{ feeInfo.billingPeriod }}</text>
          </view>
          <view class="detail-item">
            <text class="label">到期日期：</text>
            <text class="value due-date">{{ feeInfo.dueDate }}</text>
          </view>
          <view class="detail-item">
            <text class="label">房屋信息：</text>
            <text class="value">{{ feeInfo.householdInfo }}</text>
          </view>
        </view>
        <view class="fee-amount">
          <text class="amount-label">应缴金额</text>
          <text class="amount-value">¥{{ feeInfo.amount }}</text>
        </view>
      </view>
    </view>
    
    <!-- 物业公司收款码信息 -->
    <view class="payment-qr-section" v-if="paymentInfo">
      <view class="section-title">
        <u-icon name="qr-code" color="#007aff"></u-icon>
        <text>扫码支付</text>
      </view>
      
      <!-- 物业公司信息 -->
      <view class="company-info">
        <view class="company-name">{{ paymentInfo.companyName }}</view>
        <view class="company-desc" v-if="paymentInfo.paymentDescription">
          {{ paymentInfo.paymentDescription }}
        </view>
      </view>
      
      <!-- 收款二维码 -->
      <view class="qr-code-container" v-if="hasPaymentQrCodeFiles">
        <view class="qr-code-title">请扫描下方二维码进行支付</view>
        <view class="qr-code-images">
          <AppImagePreview 
            :images="paymentQrCodeFiles"
            :show-image-info="false"
            empty-text="暂无收款码"
            @preview="handleImagePreview"
            @error="handleImageError"
            @load="handleImageLoad"
          />
        </view>
        <view class="qr-code-tip">点击二维码可放大查看</view>
      </view>
      
      <!-- 支付账户信息 -->
      <view class="payment-account-info" v-if="paymentInfo.paymentAccount">
        <view class="account-title">银行转账信息</view>
        <view class="account-item">
          <text class="account-label">收款账户：</text>
          <text class="account-value">{{ paymentInfo.paymentAccount }}</text>
        </view>
        <view class="account-item" v-if="paymentInfo.paymentBank">
          <text class="account-label">开户银行：</text>
          <text class="account-value">{{ paymentInfo.paymentBank }}</text>
        </view>
      </view>
      
      <!-- 联系信息 -->
      <view class="contact-info" v-if="paymentInfo.contactPhone || paymentInfo.serviceHotline">
        <view class="contact-title">联系方式</view>
        <view class="contact-item" v-if="paymentInfo.contactPhone">
          <text class="contact-label">联系电话：</text>
          <text class="contact-value" @click="callPhone(paymentInfo.contactPhone)">{{ paymentInfo.contactPhone }}</text>
        </view>
        <view class="contact-item" v-if="paymentInfo.serviceHotline">
          <text class="contact-label">服务热线：</text>
          <text class="contact-value" @click="callPhone(paymentInfo.serviceHotline)">{{ paymentInfo.serviceHotline }}</text>
        </view>
      </view>
      
      <!-- 支付说明 -->
      <view class="payment-notice">
        <view class="notice-title">
          <u-icon name="info-circle" color="#ff9500"></u-icon>
          <text>支付说明</text>
        </view>
        <view class="notice-content">
          <text>1. 请使用微信或支付宝扫描上方二维码进行支付</text>
          <text>2. 支付时请备注房号，以便物业公司核对</text>
          <text>3. 支付完成后请保留支付凭证</text>
          <text>4. 如有疑问请联系物业公司</text>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-section" v-if="loading">
      <u-loading-icon mode="circle" size="28" color="#409EFF"></u-loading-icon>
      <text class="loading-text">正在获取收款码信息...</text>
    </view>
    
    <!-- 错误状态 -->
    <view class="error-section" v-if="errorMessage">
      <u-empty 
        text="获取收款码失败" 
        icon="error-circle"
        mode="error"
      />
      <view class="error-message">{{ errorMessage }}</view>
      <u-button 
        type="primary" 
        text="重新获取"
        @click="loadPaymentInfo"
        class="retry-button"
      />
    </view>
  </view>
</template>

<script>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store'
import { propertyFeeApi, propertyPaymentApi } from '@/api/property'
import AppImagePreview from '@/components/AppImagePreview.vue'

export default {
  name: 'Payment',
  components: {
    AppImagePreview
  },
  setup() {
    const userStore = useUserStore()
    
    // 响应式数据
    const feeInfo = ref(null)
    const paymentInfo = ref(null)
    const loading = ref(false)
    const errorMessage = ref('')
    const feeId = ref('')
    const householdId = ref('')
    
    // 计算属性：处理收款码数据
    const hasPaymentQrCodeFiles = computed(() => {
      if (!paymentInfo.value || !paymentInfo.value.paymentQrCode) {
        return false
      }
      try {
        const qrCodeFiles = JSON.parse(paymentInfo.value.paymentQrCode)
        return Array.isArray(qrCodeFiles) && qrCodeFiles.length > 0
      } catch (error) {
        console.error('解析收款码数据失败:', error)
        return false
      }
    })
    
    const paymentQrCodeFiles = computed(() => {
      if (!paymentInfo.value || !paymentInfo.value.paymentQrCode) {
        return []
      }
      try {
        const qrCodeFiles = JSON.parse(paymentInfo.value.paymentQrCode)
        return Array.isArray(qrCodeFiles) ? qrCodeFiles : []
      } catch (error) {
        console.error('解析收款码数据失败:', error)
        return []
      }
    })
    
    // 页面生命周期
    onLoad((options) => {
      if (options.feeId) {
        feeId.value = options.feeId
        loadFeeDetail(options.feeId)
      }
      if (options.householdId) {
        householdId.value = options.householdId
        loadPaymentInfo(options.householdId)
      }
    })
    
    // 方法
    const handleBack = () => {
      uni.navigateBack()
    }
    
    // 加载费用详情
    const loadFeeDetail = async (id) => {
      try {
        const response = await propertyFeeApi.getFeeDetail(id)
        if (response.code === 200) {
          feeInfo.value = response.data
          // 如果费用详情中包含房户ID，则加载收款码信息
          if (response.data.householdId && !householdId.value) {
            householdId.value = response.data.householdId
            loadPaymentInfo(response.data.householdId)
          }
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('获取费用详情失败:', error)
        uni.showToast({
          title: '获取费用详情失败',
          icon: 'none'
        })
      }
    }
    
    // 加载收款码信息
    const loadPaymentInfo = async (householdId) => {
      if (!householdId) {
        errorMessage.value = '房户信息不完整，无法获取收款码'
        return
      }
      
      loading.value = true
      errorMessage.value = ''
      
      try {
        const response = await propertyPaymentApi.getPaymentInfoByHouseholdId(householdId)
        if (response.code === 200) {
          paymentInfo.value = response.data
          console.log('获取收款码信息成功:', response.data)
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('获取收款码信息失败:', error)
        errorMessage.value = error.message || '获取收款码信息失败'
        uni.showToast({
          title: '获取收款码信息失败',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }
    
    // 图片预览事件处理
    const handleImagePreview = (data) => {
      console.log('图片预览事件:', data)
      // AppImagePreview组件会自动处理预览，这里可以添加额外的逻辑
    }

    // 图片错误事件处理
    const handleImageError = (data) => {
      console.error('图片错误事件:', data)
      uni.showToast({
        title: '图片加载失败',
        icon: 'none'
      })
    }

    // 图片加载事件处理
    const handleImageLoad = (data) => {
      console.log('图片加载事件:', data)
    }
    
    // 拨打电话
    const callPhone = (phoneNumber) => {
      uni.makePhoneCall({
        phoneNumber: phoneNumber,
        success: () => {
          console.log('拨打电话成功')
        },
        fail: (error) => {
          console.error('拨打电话失败:', error)
          uni.showToast({
            title: '拨打电话失败',
            icon: 'none'
          })
        }
      })
    }
    
    return {
      feeInfo,
      paymentInfo,
      loading,
      errorMessage,
      hasPaymentQrCodeFiles,
      paymentQrCodeFiles,
      handleBack,
      loadPaymentInfo,
      handleImagePreview,
      handleImageError,
      handleImageLoad,
      callPhone
    }
  }
}
</script>

<style lang="scss" scoped>
.payment-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.fee-info-section {
  padding: 20rpx;
  
  .fee-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .fee-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;
      
      .fee-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .fee-details {
      margin-bottom: 30rpx;
      
      .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16rpx;
        
        .label {
          color: #666;
          font-size: 28rpx;
        }
        
        .value {
          color: #333;
          font-size: 28rpx;
          
          &.due-date {
            color: #ff4757;
            font-weight: bold;
          }
        }
      }
    }
    
    .fee-amount {
      text-align: center;
      padding: 20rpx;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      
      .amount-label {
        display: block;
        color: #666;
        font-size: 28rpx;
        margin-bottom: 10rpx;
      }
      
      .amount-value {
        display: block;
        color: #ff4757;
        font-size: 48rpx;
        font-weight: bold;
      }
    }
  }
}

.payment-qr-section {
  padding: 20rpx;
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    text {
      margin-left: 10rpx;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .company-info {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .company-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .company-desc {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
    }
  }
  
  .qr-code-container {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    text-align: center;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .qr-code-title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .qr-code-image {
      margin-bottom: 20rpx;
      
      .qr-code-img {
        width: 300rpx;
        height: 300rpx;
        border-radius: 12rpx;
        border: 2rpx solid #e9ecef;
      }
    }
    
    .qr-code-tip {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .payment-account-info {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .account-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .account-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16rpx;
      
      .account-label {
        color: #666;
        font-size: 28rpx;
      }
      
      .account-value {
        color: #333;
        font-size: 28rpx;
        font-weight: bold;
      }
    }
  }
  
  .contact-info {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .contact-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .contact-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16rpx;
      
      .contact-label {
        color: #666;
        font-size: 28rpx;
      }
      
      .contact-value {
        color: #007aff;
        font-size: 28rpx;
        text-decoration: underline;
      }
    }
  }
  
  .payment-notice {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .notice-title {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      text {
        margin-left: 10rpx;
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .notice-content {
      text {
        display: block;
        font-size: 26rpx;
        color: #666;
        line-height: 1.6;
        margin-bottom: 10rpx;
      }
    }
  }
}

.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 20rpx;
  
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.error-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 20rpx;
  
  .error-message {
    margin: 20rpx 0;
    font-size: 28rpx;
    color: #ff4757;
    text-align: center;
  }
  
  .retry-button {
    margin-top: 20rpx;
  }
}
</style>
